<template>
  <Dialog v-model="dialogVisible" title="编辑" width="450">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item :label="curRows.type == 1 ? '上级节点' : '目标文件组'" prop="pid">
        <el-tree-select
          style="width: 100%"
          ref="treeGroupRef"
          v-model="formData.pid"
          value-key="id"
          node-key="id"
          :data="treeData"
          :props="{ label: 'name' }"
          :render-after-expand="false"
          placeholder="请选择上级节点"
          :default-expanded-keys="['0']"
          check-strictly
          clearable
        />
      </el-form-item>
      <el-form-item :label="curRows.type == 2 ? '文件名称' : '文件组名称'" prop="name">
        <ns-input v-model="formData.name" placeholder="请输入" />
      </el-form-item>
      <template v-if="curRows.type !== 2">
        <el-form-item label="归属机构:" prop="deptId">
          <el-cascader
            ref="deptCascader"
            v-model="formData.deptId"
            placeholder="请选择归属机构"
            style="width: 100%"
            :props="cascaderProps"
            :options="deptList"
            filterable
            clearable
            value-on-clear=""
            :filter-method="sysFilterMethod"
          />
        </el-form-item>
        <el-form-item label="归属系统:" prop="sysId">
          <el-cascader
            ref="systemCascader"
            v-model="formData.sysId"
            placeholder="请选择归属系统"
            :props="systemCascaderProps"
            :options="systemList"
            style="width: 100%"
            filterable
            clearable
            value-on-clear=""
            :filter-method="sysFilterMethod"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { multiUpdateFile, getFileInfo } from '@/api/develop/file'
import { useGroupTree } from '@/hooks/web/useFileTree'
import { cloneDeep } from 'lodash-es'
import { handleTree } from '@/utils/tree'
import { getSimpleDeptList } from '@/api/system/dept'
import { sysFilterMethod } from '@/utils/selectFilter'
import { getSimpleSystemList } from '@/api/asset/taskManage'
const { treeGroupData, reFreshTreeData } = useGroupTree()
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

let curIds: string[] = []
let curRows = ref<Record<string, any>>({})
const treeData = ref()
/** 打开弹窗 */
const open = async (ids: string[], pid?: string, row?: any) => {
  await getSystemList()
  await getDeptList()
  const data = await getInfo(row)
  curIds = ids
  if (pid) formData.value.pid = pid
  dialogVisible.value = true
  curRows.value = row
  formData.value.name = row.name
  formData.value.deptId = data.deptId
  formData.value.sysId = data.sysId
  const treeGroup = cloneDeep(treeGroupData.value)
  treeData.value = traverseTree(treeGroup)
}
const deptList = ref([])
const systemList = ref([])
const systemCascaderProps = reactive({
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
})
const cascaderProps = reactive({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
})

const getInfo = async (row) => {
  const { data } = await getFileInfo({ id: row.id })
  return data
}

function traverseTree(data) {
  const updatedTree = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.id == curRows.value.id) {
      node.disabled = true
      disableDescendants(node.children)
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}

function disableDescendants(children) {
  if (children && children.length > 0) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      children[i].disabled = true // 将子孙节点设置为 disabled
      disableDescendants(child.children) // 递归将子孙节点的子孙节点都设置为 disabled
      children[i] = child
    }
  }
}

const formData = ref({
  pid: '',
  name: undefined,
  deptId: '',
  sysId: ''
})
const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})
const formRules = computed(() => ({
  name: [{ required: true, message: '文件组名称不能为空', trigger: ['blur', 'change'] }],
  pid: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }]
}))
const formRef = ref<FormInstance>() // 表单 Ref

async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}
async function getSystemList() {
  const data = await getSimpleSystemList()
  systemList.value = handleTree(data, 'id', 'pid')
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value?.validate()

  // 提交请求
  formLoading.value = true
  try {
    const data = toRaw(formData.value)
    const params_ = curIds.map((id) => {
      return {
        id: id,
        ...data,
        deptId: formData.value.deptId || '0'
      }
    })
    await multiUpdateFile(params_)
    message.success(t('common.updateSuccess'))
    reFreshTreeData()
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false
  curIds = []
  curRows.value = {}
  formData.value = {
    pid: '',
    name: undefined,
    deptId: '',
    sysId: ''
  }
  formRef.value?.resetFields()
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped>
// .form-wrap {
//   height: 120px;
//   display: flex;
//   flex-direction: column;
//   justify-content: center;
//   :deep(.el-form-item) {
//     margin-bottom: 0;
//   }
// }
</style>
